package com.naihe.anderson.sms.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.ContactUser;
import com.naihe.anderson.sms.manager.ContactMgr;


public class SignatureGridAdapter extends BaseAdapter {

    private Context myContext;
    private ContactMgr contactMgr;
    private List<String> objects;

    public SignatureGridAdapter(Context myContext, List<String> objects) {
        this.myContext = myContext;
        this.objects = objects;
        contactMgr = ((NhSmsApp)myContext.getApplicationContext()).getContactMgr();
    }
    
    @Override
    public int getCount() {
        return objects.size();

    }

    @Override
    public String getItem(int position) {
    	if(objects == null) return null;
        return objects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(myContext);
            view = inflater.inflate(R.layout.signature_grid_item, null);
        } else {
            view = convertView;
        }

        TextView name = (TextView) view.findViewById(R.id.grTextTitle);
        TextView number = (TextView) view.findViewById(R.id.number);
        ImageView headImage = (ImageView) view.findViewById(R.id.contactImage);
        
        String signatureNumber = objects.get(position);
        ContactUser contactUser = contactMgr.getContactUserById(contactMgr.getContactIdByPhoneNum(signatureNumber));
        if(contactUser != null){
        	name.setText(contactUser.getName());
        	if(contactUser != null && contactUser.getPhotoId() > 0){
        		headImage.setBackgroundDrawable(new BitmapDrawable(contactMgr.getContactHeadImgByPhotoId(contactUser.getPhotoId())));
			} else {
				headImage.setBackgroundDrawable(myContext.getResources().getDrawable(R.drawable.default_head));
			}
        	number.setVisibility(View.VISIBLE);
        	number.setText(signatureNumber);
        } else {
        	number.setVisibility(View.GONE);
        	headImage.setBackgroundDrawable(myContext.getResources().getDrawable(R.drawable.default_head));
        	name.setText(signatureNumber);
        }
        
        contactUser = null;
        signatureNumber = null;
        return view;

    }
    
}
